package com.apesay.security;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apesay.exception.ServiceException;
import com.apesay.service.auth.AccountService;
import com.apesay.service.auth.PermissionService;
import com.apesay.utils.DataUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha384Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;

@Service
public class ShiroSecurity extends AuthorizingRealm{
	@Autowired
	private AccountService accountService;
	@Autowired
	private PermissionService permissionService;
	//获取授权信息
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String userId=(String) principalCollection.getPrimaryPrincipal();
		if(DataUtils.isNotEmpty(userId)){
			SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
			//获取用户的授权信息
			JSONArray permissionArray;
			try {
				permissionArray = permissionService.getPermissionsByUserId(userId);
				Set<String> permissions=new HashSet<String>();
				for(int i=0;i<permissionArray.size();i++){
					permissions.add(permissionArray.getJSONObject(i).getString("key"));
				}
				authorizationInfo.addStringPermissions(permissions);
			} catch (ServiceException e) {
				e.printStackTrace();
			}
			return authorizationInfo;
		}
		return null;
		
	}
	//登录验证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
		String username=String.valueOf(usernamePasswordToken.getUsername());
		JSONObject userObject;
		AuthenticationInfo info=null;
		try {
			userObject = accountService.findByName(username);
			if(null!=userObject){
				String password=new String(usernamePasswordToken.getPassword());
				password=new Sha384Hash(password).toBase64();
				if(password.equals(userObject.getString("password"))){
					//密码校验移交给了shiro提供的一个接口实现类
					info=new SimpleAuthenticationInfo(userObject.getString("username"),userObject.getString("password"),getName());
				}else{
					throw new CustomAuthenticationException(CustomAuthenticationException.AuthenticateError, "用户名或密码不正确");
				}
			}else{
				throw new CustomAuthenticationException(CustomAuthenticationException.AccountNotExist, "账户不存在");
			}
		} catch (ServiceException e) {
			e.printStackTrace();

		}
		return info;
	}
	@PostConstruct  
    public void initCredentialsMatcher() {  
		//该句作用是重写shiro的密码验证，让shiro用我自己的验证  
        setCredentialsMatcher(new CustomCredentialsMatcher());  
  
    }
}
